//
//  SinaRefreshView.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/19.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit
import SnapKit

enum RefreshState: Int {
    case Normal = 0
    case Ready
    case Refreshing
}


class SinaRefreshView: UIControl {

    //控件高度
    let viewHeight: CGFloat = 60
    
    //图片框
    private lazy var iv_refresh = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    
    //箭头
    private lazy var iv_arrow = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    //指示Lable
    private lazy var lb_desc = UILabel(title: "下拉起飞", font: 14, color: UIColor.orange)
    //菊花
    private lazy var iv_indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    
    
    //滚动视图
    var scrollView: UIScrollView?
    
    
    //当前状态
    var currentState: RefreshState = .Normal{
        
        didSet{
            
            switch currentState {
            case .Normal:
                lb_desc.text = "下拉起飞"
                iv_indicator.stopAnimating()
                iv_arrow.isHidden = false
                
                UIView.animate(withDuration: 0.5, animations: {
                    self.iv_arrow.transform = CGAffineTransform.identity
                })
                
                if oldValue == .Refreshing{
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - self.viewHeight
                    })
                }
                
                
            case .Ready:
                lb_desc.text = "松手刷新"
                
                UIView.animate(withDuration: 0.5, animations: { 
                    self.iv_arrow.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
                
                
                
            case .Refreshing:
                iv_arrow.isHidden = true
                iv_indicator.startAnimating()
                lb_desc.text = "正在刷新"
                
                //发送事件
                sendActions(for: .valueChanged)
                
                //悬停效果
                UIView.animate(withDuration: 0.25, animations: {
                    self.scrollView!.contentInset.top = self.scrollView!.contentInset.top + self.viewHeight
                })
                
            }
            
            
        }
        
    }
    
    
    //停止刷新的方法
    func endRefreshing() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.currentState = .Normal
        }
    }
    
    
    
    
    //重写初始化方法
    init() {
        super.init(frame: CGRect(x: 0, y: -viewHeight, width: screenWidth, height: viewHeight))
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setupUI() {
        backgroundColor = UIColor.clear
        
        lb_desc.font = UIFont.systemFont(ofSize: 14)
        lb_desc.text = "下拉刷新"
        lb_desc.textColor = UIColor.darkGray
        
        
        self.addSubview(iv_refresh)
        self.addSubview(iv_arrow)
        self.addSubview(lb_desc)
        self.addSubview(iv_indicator)
        
        
        //约束
        
        iv_refresh.snp.makeConstraints { (make) in
            
            make.leading.trailing.bottom.equalTo(self)
            
        }
        
        
        
        iv_arrow.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
            
        }
        
        lb_desc.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(self)
            make.leading.equalTo(iv_arrow.snp.trailing).offset(5)
            
        }
        
        iv_indicator.snp.makeConstraints { (make) in
            
            make.center.equalTo(iv_arrow)
            
        }
    }
    

    
    // MARK:
    // MARK: - tableView添加了该视图时会触发的方法
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        //看看父控件是不是scrollView
        if let fatherView = newSuperview as? UIScrollView{
            self.scrollView = fatherView
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    
    
    
    
    // MARK:
    // MARK: - 实现监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let offsetY = self.scrollView!.contentOffset.y
        let targatOffsetY = -(scrollView!.contentInset.top + viewHeight)
        
        //通过两个offsetY比较  来改变状态
        //正在拖拽
        if scrollView!.isDragging{
            if currentState == .Normal && offsetY < targatOffsetY{
                currentState = .Ready
            }else if currentState == .Ready && offsetY > targatOffsetY{
                currentState = .Normal
            }
            
        }else{
            if currentState == .Ready{
                currentState = .Refreshing
            }
            
        }
        
        
        
    }
    
    
    
    
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
}
